package cn.sjlink.appraise.service.impl;

import cn.sjlink.appraise.constants.ConsignmentStatus;
import cn.sjlink.appraise.dao.*;
import cn.sjlink.appraise.entity.*;
import cn.sjlink.appraise.form.AppraiseEnsureForm;
import cn.sjlink.appraise.form.AppraiseForm;
import cn.sjlink.appraise.form.PutFinishForm;
import cn.sjlink.appraise.service.AppraiseGoodsService;
import cn.sjlink.appraise.vo.AppraiseListVo;
import cn.sjlink.appraise.vo.SelectVo;
import cn.sjlink.config.BusinessException;
import cn.sjlink.store.dao.StoreShopSiteMapper;
import cn.sjlink.store.entity.StoreShopSite;
import cn.sjlink.util.*;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.security.provider.MD5;

import java.util.ArrayList;
import java.util.List;

@Service
public class AppraiseGoodsServiceImpl implements AppraiseGoodsService {

    private static final String SIGN_KEY = "SJQStack";
    private static final String OPEN_URL = "https://w3.morninggo.cn/tiamoo/push/open";
    private final Logger logger = Logger.getLogger(getClass());
    @Autowired
    private AppraiseGoodsStackMapper appraiseGoodsStackMapper;
    @Autowired
    private AppraiseGoodsItemMapper appraiseGoodsItemMapper;
    @Autowired
    private YoshopAppraiseGoodsMapper appraiseGoodsMapper;
    @Autowired
    private YoshopWaybillMapper yoshopWaybillMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private YoshopAppraiseGoodsLogMapper appraiseGoodsLogMapper;
    @Autowired
    private StoreShopSiteMapper shopSiteMapper;
    @Autowired
    private AccessTokenUtil accessTokenUtil;

    @Override
    public Result submitAppraise(AppraiseForm appraiseForm) {
        StoreShopSite storeShopSite = shopSiteMapper.findByDeviceNo(appraiseForm.getStackNo());
        String sNowDateTime = DateUtil.getSNowDateTime();
        YoshopAppraiseGoodsStack appraiseGoodsStack = new YoshopAppraiseGoodsStack();
        appraiseGoodsStack.setAppraiseImages(appraiseForm.getImages());
        appraiseGoodsStack.setOrderNo(getConsignmentNo());
        appraiseGoodsStack.setStackNo(appraiseForm.getStackNo());
        appraiseGoodsStack.setStackName(storeShopSite.getSiteName());
        appraiseGoodsStack.setUserId(appraiseForm.getUserId());
        appraiseGoodsStack.setStatus(1);
        appraiseGoodsStack.setCreateTime(sNowDateTime);
        List<YoshopAppraiseGoodsItem> goodsItems = new ArrayList<>();
        if(appraiseGoodsStackMapper.insertUseGeneratedKeys(appraiseGoodsStack)==1){
            List<SelectVo> selectList = appraiseForm.getSelectList();
            for (SelectVo selectVo : selectList) {
                YoshopAppraiseGoodsItem yoshopAppraiseGoodsItem = new YoshopAppraiseGoodsItem();
                yoshopAppraiseGoodsItem.setItemSelectValue(selectVo.getSelectName());
                yoshopAppraiseGoodsItem.setItemIdentifyValue(selectVo.getSelectValue());
                yoshopAppraiseGoodsItem.setWxappId(10001);
                yoshopAppraiseGoodsItem.setCreateTime(sNowDateTime);
                yoshopAppraiseGoodsItem.setAppraiseGoodsId(0);
                yoshopAppraiseGoodsItem.setStatus(10);
                yoshopAppraiseGoodsItem.setStackId(appraiseGoodsStack.getId());
                yoshopAppraiseGoodsItem.setIdentifyIdentifyValue("");
                yoshopAppraiseGoodsItem.setIdentifySelectValue("");
                goodsItems.add(yoshopAppraiseGoodsItem);
            }
            if(goodsItems.size()>0){
                appraiseGoodsItemMapper.insertList(goodsItems);
            }
            return new Result(true,"提交成功",appraiseGoodsStack.getOrderNo());
        }
        return new Result(false,"提交失败，请重试");
    }

    @Override
    public Result ensureAppraise(AppraiseEnsureForm appraiseEnsureForm) throws BusinessException {
        YoshopAppraiseGoods appraiseGoods = appraiseGoodsMapper.findByOrderNo(appraiseEnsureForm.getOrderNo());
        if(appraiseGoods!=null && appraiseGoods.getStatus() == ConsignmentStatus.ASSESS_FINISH){
            if(appraiseEnsureForm.getOperateType()==2 && appraiseGoods.getAppraiseType()==1){
                throw new BusinessException("该商品不可回收，请选择寄卖类型");
            }
            appraiseGoods.setType(appraiseEnsureForm.getOperateType());
            appraiseGoods.setEstimatedPrice(appraiseEnsureForm.getOperateType()==1?appraiseGoods.getDeliveryPrice():appraiseGoods.getStorePrice());
            appraiseGoodsMapper.updateByPrimaryKeySelective(appraiseGoods);
            return new Result(true,"操作成功");
        }
        throw new BusinessException("该商品已操作完成，请刷新重试");
    }

    @Override
    public Result waitSendList(Long userId, Integer page, Integer pageSize) {
        if(page != null && pageSize != null){
            PageHelper.startPage(page, pageSize);
        }else{
            PageHelper.startPage(0, 10);
        }
        List<AppraiseListVo> appraiseListVos = appraiseGoodsMapper.waitSendList(userId);
        return new Result(new PageInfo<>(appraiseListVos));
    }

    @Override
    public Result putFinish(PutFinishForm putFinishForm) throws BusinessException {
        StoreShopSite shopSite = shopSiteMapper.findByDeviceNo(putFinishForm.getStackNo());
        String[] split = putFinishForm.getOrderNo().split(",");
        if(split.length>0){
            List<YoshopAppraiseGoods> appraiseGoodsList = appraiseGoodsMapper.findByOrderNos(split);
            for (YoshopAppraiseGoods yoshopAppraiseGoods : appraiseGoodsList) {
                int beforeStatus = yoshopAppraiseGoods.getStatus();
                yoshopAppraiseGoods.setStatus(ConsignmentStatus.EXPRESS);
                appraiseGoodsMapper.updateByPrimaryKeySelective(yoshopAppraiseGoods);
                YoshopWaybill yoshopWaybill = new YoshopWaybill();
                yoshopWaybill.setShopId(shopSite.getShopId());
                yoshopWaybill.setOrderNo(yoshopAppraiseGoods.getValuationNumber());
                yoshopWaybill.setGoodsNo(yoshopAppraiseGoods.getGoodsNo());
                yoshopWaybill.setUserId(putFinishForm.getUserId());
                yoshopWaybill.setType(10);
                yoshopWaybill.setStatus(21);
                yoshopWaybill.setStackNo(putFinishForm.getStackNo());
                yoshopWaybill.setLatticeId(putFinishForm.getLatticeId());
                yoshopWaybill.setPickCode(CaptchaUtil.getCaptcha(6));
                yoshopWaybill.setBrandId(yoshopAppraiseGoods.getBrandId());
                yoshopWaybill.setCategoryId(yoshopAppraiseGoods.getCategoryId());
                yoshopWaybill.setWaybillType(4);
                yoshopWaybill.setCreateTime(DateUtil.getSNowDateTime());
                yoshopWaybill.setIsBack(0);
                yoshopWaybillMapper.insertUseGeneratedKeys(yoshopWaybill);
                //操作日志
                YoshopAppraiseGoodsLog yoshopAppraiseGoodsLog = new YoshopAppraiseGoodsLog();
                yoshopAppraiseGoodsLog.setAppraiseGoodsId(yoshopAppraiseGoods.getAppraiseGoodsId());
                yoshopAppraiseGoodsLog.setBeforeStatus(beforeStatus);
                yoshopAppraiseGoodsLog.setAfterStatus(ConsignmentStatus.EXPRESS);
                yoshopAppraiseGoodsLog.setStoreUserId(0);
                yoshopAppraiseGoodsLog.setIsUser(1);
                yoshopAppraiseGoodsLog.setUserId(yoshopAppraiseGoods.getUserId());
                yoshopAppraiseGoodsLog.setMemo("商品已放入小栈保险柜，点位名称："+shopSite.getSiteName());
                yoshopAppraiseGoodsLog.setCreateTime(DateUtil.getSNowDateTime());
                appraiseGoodsLogMapper.insertUseGeneratedKeys(yoshopAppraiseGoodsLog);
            }
            return new Result(true,"操作成功");
        }
        throw new BusinessException("参数错误，获取订单信息失败");
    }

    @Override
    public Result checkCode(String pickCode, String stackNo, String sign)throws BusinessException {
        if(StringUtils.isEmpty(sign)){
            throw new BusinessException("参数错误");
        }
        String encode = MD5Util.encode(pickCode + "|" + stackNo + "|" + SIGN_KEY);
        if(encode.equalsIgnoreCase(sign)){
            List<YoshopWaybill> waybills = yoshopWaybillMapper.findByStack(stackNo, pickCode);
            if(waybills.size()>0){
                return new Result(true,"校验成功");
            }
            return new Result(false,"取件码无效");
        }
        throw new BusinessException("签名错误");
    }

    /*public static void main(String[] args) {
        String encode = MD5Util.encode("021302|S062202103104|" + SIGN_KEY);
        System.out.println(encode);
    }*/

    @Override
    public Result pickNotice(String pickCode, String stackNo,String sign) throws Exception {
        if(StringUtils.isEmpty(sign)){
            throw new BusinessException("参数错误");
        }
        String encode = MD5Util.encode(pickCode + "|" + stackNo + "|" + SIGN_KEY);
        if(encode.equalsIgnoreCase(sign)){
            Long shopManage = shopSiteMapper.findShopManage(stackNo);
            List<YoshopWaybill> waybills = yoshopWaybillMapper.findByStack(stackNo, pickCode);
            if(waybills.size()>0){
                String stackToken = accessTokenUtil.getStackToken();
                String s = HttpClientUtil.doPostWithHeader(OPEN_URL + "?matrixId=" + waybills.get(0).getLatticeId(), "", "Bearer " + stackToken);
                logger.info(s);
                JSONObject jsonObject = JSONObject.parseObject(s);
                if((boolean)jsonObject.get("success")){
                    for (YoshopWaybill waybill : waybills) {
                        waybill.setStatus(ConsignmentStatus.WAIT_UPLOAD);
                        waybill.setPickCode("");
                        yoshopWaybillMapper.updateByPrimaryKeySelective(waybill);
                        //保存操作日志
                        YoshopAppraiseGoodsLog yoshopAppraiseGoodsLog = new YoshopAppraiseGoodsLog();
                        yoshopAppraiseGoodsLog.setAppraiseGoodsId(waybill.getAppraiseGoodsId());
                        yoshopAppraiseGoodsLog.setBeforeStatus(ConsignmentStatus.EXPRESS);
                        yoshopAppraiseGoodsLog.setAfterStatus(ConsignmentStatus.EXPRESS);
                        yoshopAppraiseGoodsLog.setIsUser(2);
                        yoshopAppraiseGoodsLog.setUserId(shopManage==null?0L:shopManage);
                        yoshopAppraiseGoodsLog.setStoreUserId(0);
                        yoshopAppraiseGoodsLog.setMemo("商品已从保险柜取出");
                        yoshopAppraiseGoodsLog.setCreateTime(DateUtil.getSNowDateTime());
                        appraiseGoodsLogMapper.insertUseGeneratedKeys(yoshopAppraiseGoodsLog);
                    }
                    return new Result(true,"箱门已打开");
                }
                Object error = jsonObject.get("error");
                return new Result(false,"开锁失败",error);
            }
            return new Result(false,"取件码无效");
        }
        return new Result(false,"签名错误");
    }

    private String getConsignmentNo(){
        String cday = DateUtil.getSNowDate();
        long incr ;
        if(redisUtil.get(cday)!=null){
            incr = redisUtil.incr(cday, 1);
        }else{
            redisUtil.set(cday,1);
            incr = 1;
        }
        return DateUtil.getSNowDateTimeDB() + incr;
    }
}
